package com.ithuameng.notice.netty;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ithuameng.notice.config.ApplicationContextProvider;
import com.ithuameng.notice.util.R;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户请求一个Websocket
 * 服务器查询队列中rabbitMQ消息的个数，并返回给用户界面
 * (用户只请求一次，通知系统自动推送其余的)
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ObjectMapper MAPPER = new ObjectMapper();

    private SimpleMessageListenerContainer sysNoticeContainer = (SimpleMessageListenerContainer) ApplicationContextProvider
            .getApplicationContext().getBean("sysNoticeContainer");

    public static ConcurrentHashMap<String, Channel> userChannelMap = new ConcurrentHashMap<>();

    private RabbitTemplate rabbitTemplate = ApplicationContextProvider.getApplicationContext().getBean(RabbitTemplate.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 标记超级管理员信道
        Channel channel = ctx.channel();
        userChannelMap.put("admin", channel);
        // 获取系统队列数量
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        String queueName = "system_notice_queue";
        Properties queueProperties = rabbitAdmin.getQueueProperties(queueName);
        int noticeCount = 0;
        if (queueProperties != null) {
            noticeCount = (int) queueProperties.get("QUEUE_MESSAGE_COUNT");
        }
        // 将查询到的消息数量输出给前端
        HashMap<String, Integer> countMap = new HashMap<>();
        countMap.put("sysNoticeCount", noticeCount);
        R result = new R<>(true, 200, "查询成功", countMap);
        channel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(result)));
        // 清空队列
        if (noticeCount > 0) {
            rabbitAdmin.purgeQueue(queueName, true);
        }
        // 监听队列
        sysNoticeContainer.addQueueNames(queueName);
    }
}
